<template>
    <view class="">
        <!-- #ifdef MP-WEIXIN --> 
        <top-nav :inner-title="title" is-show-home="true" is-fixed="true" :navH="navH" :n="n" is-white="bg-white" opacity="1"></top-nav>
        <view  :style="{height:navH+ 'px'}"></view>
        <!-- #endif -->  
        <view class="load_before" v-if="hideOver" :style="{opacity: loadOver ? 1 : 0}">
            
        </view>
        <view class="content">
            <image class="top_image" mode="aspectFit" src="http://img1.birdback.org/a/2f/4c/2f4c8975953947a18cda8be281be7822.png"></image>
            <view class="opacity_content flex column">
                <view class="bind_phone" v-if="bindPhoneShow">
                    <view class="list_title flex">
                        <view class="slide"></view>
                        <view class="title">同学快跑</view>
                        <view class="slide"></view>
                    </view>
                    <view class="item">
                        <input class="phone dark_text" :value='phone' placeholder="请输入您的手机号" placeholder-style="color:#999" maxlength='11' type='number' @input="phoneEvent"/>
                    </view>
                    <view class="sunui item" v-if="phone.length == 11">
                        <view class="sunui-title">右滑拖动验证</view>
                        <sunui-mverify @change="mverify"></sunui-mverify>
                    </view>
                    <view class="item flex">
                        <input class="phone dark_text" :value='code' placeholder="请输入短信验证码" placeholder-style="color:#999" type='number' @input="codeEvent"/>
                        <view class="code flex" :class="phone.length == 11 && verified ? 'orange' : ''" @click="getCode()">
                            <block v-if="s==0">重新发送</block>
                            <block v-else>{{sending? s+'s':'发送验证码'}}</block>
                        </view>
                    </view>
                    <view class="item flex">
                        <view class="red_bar" :class="phone.length==11 && code.length == 4 ? '':'gray_bar'" @click="submit()">立即登录</view>
                    </view>
                    
                </view>
                <view class="packet" v-if="new_redpacket.reduction">
                    <image class="packet-bg" src="http://img1.birdback.org/Combined%20Shape%20Copy@3x.png"></image>
                    <view class="packet_top">
                        <view class="radius left">
                            <view class=""></view>
                        </view>
                        <view class="packet_left">
                            <view class="packet_name flex">
                                <view>{{new_redpacket.title}}</view>
                                <view class="suprise_tag flex">
                                    <view class="suprise_icon"></view>
                                    <view>特别惊喜</view>
                                </view>
                            </view>
                            <view class="packet_deadline">满{{new_redpacket.full}}可用</view>
                        </view>
                        <view class="packet_right">
                            <view class="packet_value">¥<text>{{new_redpacket.reduction}}</text></view>
                        </view>
                        <view class="radius right">
                            <view class=""></view>
                        </view>
                    </view>
                    <view class="packet_bottom">
                        <view class="packet_tip"> 
                            <view class="tip">{{new_redpacket.end_time}} </view>
                            <view class="red_text" @click="goHome()">去使用></view>
                        </view>
                    </view>
                </view>
                <view class="packet" v-if="mine_packet.reduction">
                    <image class="packet-bg" src="http://img1.birdback.org/Combined%20Shape%20Copy@3x.png"></image>
                    <view class="packet_top">
                        <view class="radius left">
                            <view class=""></view>
                        </view>
                        <view class="packet_left">
                            <view class="packet_name">{{mine_packet.p_name}}</view>
                            <view class="packet_deadline">满{{mine_packet.full}}可用</view>
                        </view>
                        <view class="packet_right">
                            <view class="packet_value">¥<text>{{mine_packet.reduction}}</text></view>
                        </view>
                        <view class="radius right">
                            <view class=""></view>
                        </view>
                    </view>
                    <view class="packet_bottom">
                        <view class="packet_tip"> 
                            <view class="tip">{{mine_packet.end_time}} </view>
                            <view class="red_text" @click="goHome()">去使用></view>
                        </view>
                    </view>
                </view>
                <view class="packet" v-if="no_right || no_get">
                    <image class="packet-bg" src="http://img1.birdback.org/Combined%20Shape%20Copy@3x.png"></image>
                        <view class="packet_close flex">
                           <block v-if="no_right">今日次数已领完</block>
                           <block v-if="no_get">该红包已领完</block>
                        </view>
                    <view class="packet_bottom"></view>
                </view>
                <view class="phone_content" v-if="mine_packet.phone">
                    <text>领券手机号：{{mine_packet.phone}}</text>
                    <!-- <text  class="red_text">修改></text> -->
                </view>
                <view class="red_bar" @click="goHome()" v-if="mine_packet.reduction || new_packet.reduction">立即使用</view>
                <!-- <button open-type="share" class="red_bar" data-id="1">邀请好友再得10元</button>  -->
            </view>
            <view class="person_list flex column" v-if="all_packet.length>0">
                <view class="list_title flex">
                    <view class="slide"></view>
                    <view class="title">看看大家手气</view>
                    <view class="slide"></view>
                </view>
                <view class="scroll flex column">
                    <view class="list_card flex" v-for="(item,index) in all_packet" :key="index">
                        <image class="per_image" :src='item.u_face ? item.u_face : "../../static/face13x.png"'></image>
                        <view class="per_middle">
                            <view class="per_name">{{item.u_name}}</view>
                            <view class="per_time">{{item.add_time}}</view>
                        </view>
                        <view class="per_right">
                            <view class="per_money">{{item.reduction}}元</view>
                            <view class="red_icon flex" v-if="item.is_max==1">
                                <image class="lucky_dog" src="http://img1.birdback.org/a/72/d4/72d4940195ed87264db010b9a0095f16.png"></image>
                                <text>手气最佳</text>
                            </view>
                        </view>
                        
                    </view>
                </view>
                <view class="red_text">
                  <!--  <block v-if="hasMax && !mineIsMax && mine_packet.reduction">只差一点点，大包就是你的啦～</block> -->
                    <block v-if="!hasMax">手气最佳尚未出现，稍后揭晓～</block>
                </view>
            </view>
            <view class="person_list flex column">
                <view class="list_title flex">
                    <view class="slide"></view>
                    <view class="title">活动规则</view>
                    <view class="slide"></view>
                </view>
                <view class="rule_list">
                    <text>1.下单即可分享红包给好友或者微信群；</text>
                    <text>2.每个分享红包链接仅限{{packet_num}}人领取；</text>
                    <text>3.每个分享红包链接会按领取顺序发放一个随机面额的大红包；</text>
                    <text>4.每人每天有5次领取红包机会；</text>
                    <text>5.红包仅限在线支付使用，且收餐人手机号、领取红包时输入的手机号和账号中的手机号需为同一手机号；</text>
                    <text>6.红包可以与满减、折扣等其他优惠叠加使用，首单红包不可叠加使用；</text>
                    <text>7.红包可以在同学快跑小程序下单时选择在线支付时使用；</text>
                    <text>8.其他未尽事宜，请咨询在线客服</text>
                </view>
            </view>
        </view>
        
     <cascade-box
           class="cascade_box" 
           :animationData="animationData" 
           :prov="prov" 
           :city="city" 
           :school="school"
           :value = "cascadeVal" 
           :column1="1"
           :column2="1"
           :column3="2.5"
           @cascadeCancel="cancelEvent()"
           @cascadeEnter="enterEvent()" 
           @cascadeChange="bindChange()"
    >
    </cascade-box>
        <view class='group-detail-box login_tip' v-if="loginShow">
            <view class="group-mask"></view>
            <view class="group-detail-medium flex column">
                    <image class="login_bg" src="http://img1.birdback.org/a/fe/95/fe95222cd63905bb2c3888ed1f357654.png"></image>
                    <!-- #ifdef MP-WEIXIN -->
                    <button class="login_bt" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
                        <image src="http://img1.birdback.org/a/e1/81/e181295849989a5fc320c493e6e19307.png"></image>
                    </button> 
                    <!-- #endif -->
                    <!-- #ifdef MP-ALIPAY -->
                    <button class="login_bt" open-type="getAuthorize" @getAuthorize="onGetAuthorize" @error="onAuthError" scope='phoneNumber'>
                         <image src="http://img1.birdback.org/a/9b/bb/9bbb60f3dee9d3ea388c1a1853e128fc.png"></image>
                    </button>  
                    <!-- #endif -->
            </view>
        </view>
    
    </view>
</template>

<script>
    import uniFly     from 'unifly';
	import request    from '../../../common/request.js';
	import $api_base  from '../../../api/api_base.js';
	import topNav     from '@/template/topnav/index.vue';
    import cascadeBox from '@/template/cascade/index.vue';
	import event      from '../../../common/event.js';
    import sunuiMverify from '@/components/sunui-mverify/sunui-mverify.vue';
	export default {
		components: { topNav,cascadeBox, sunuiMverify },
		data() {
			return {
				navH: 0,
				n: 0,
				title:'同学快跑分享红包',
                rp_id:0,
                all_packet:[],
                mine_packet:{},
                new_redpacket:{},
                prov: [],
                city: [],
                school: [],
                school_list: [],
                prov_index: 0,
                city_index: 0,
                school_index: 0,
                selectRegion: {},
                selectSchoolId: 0,
                schoolId: 0,
                animationData: {},
                phone: '',
                code: '',
                verified: false,
                sending: false,
                isOK: false,
                s: 60,
                activeTimer: null,
                bindPhoneShow: false,
                getNumberShow: false,
                loginShow: false,
                mineIsMax: false,
                hasMax: false,
                loadOver: true,
                hideOver: true,
                no_right: false,
                no_get:false,
                packet_num:0,
                firstShow:0
			}
		},
		onLoad(options) {
            this.rp_id    = options.rp_id || 0;
            this.navH	  = getApp().globalData.navHeight;
            this.n		  = getApp().globalData.n;
            this.loadData();
            var schoolId  = 0;
            schoolId      = getApp().globalData.schoolId || 0;
            this.schoolId = schoolId;
		},
        onShow: function(){
            var self = this;
            var schoolId = self.schoolId;
            var has_location = uni.getStorageSync('HAS_LOCATION') || false;
            if (schoolId > 0 || has_location) {
            	//不再获取地理位置
            	self.initData();
            } else {
            	uni.getLocation({
            		type: 'wgs84',
            		success: function(l) {
            			var latitude = l.latitude;
            			var longitude = l.longitude;
            			getApp().longLat = longitude + ',' + latitude;
            			uni.setStorageSync('HAS_LOCATION', getApp().longLat);
            			self.initData();
            		},
            		fail: function() {
            			var showLocalButton = uni.getStorageSync('SHOW_LOCAL_BUTTON') || false;
            			if (!showLocalButton) {
            				uni.setStorageSync('SHOW_LOCAL_BUTTON', 1);
            				self.loadText = '无法获取地理位置';
            				self.noAddress = true;
            				uni.showModal({
            					content: '外卖送餐需要您的地理位置',
            					confirmText: '去开启',
            					success: function(res) {
            						if (res.confirm) {
            							uni.openSetting({
            								success: function(res) {}
            							});
            						} else {
            							self.noAddress = true;
            						}
            					}
            				});
            			} else {
            				self.initData();
            			}
            		}
            	});
            }
        },
		methods:{
            beforeInitData() {
            	var date = new Date();
            	var self = this;
            	var time = parseInt(date.getTime() / 1000);
            	if (self.shopInfoList.length == 0) {
            		self.lockTime = time;
            		self.lock = false;
            	}
            	
            },
            initData() {
            	var date = new Date();
            	var self = this;
            	var time = parseInt(date.getTime() / 1000);
            	console.log(time - self.lockTime);
            	if (time - self.lockTime > 500) {
            		self.loadpacketList();
            		self.lockTime = time;
            	}
            },
            loadData() {
            	var self = this;
            	if (self.lock) return false;
            	self.lock = true;
            	self.loginReg().then(function() {
            		//定位
            		var params = {
            			long_lat: getApp().longLat,
            			school_id: self.schoolId
            		};
            		$api_base.post($api_base.homeIndex,params).then(function(res) {
            			var data = res.data;
            			if (data.ok == 2) {         //新用户
            				getApp().globalData.schoolInfo = data.schoolInfo;
            				getApp().globalData.userInfo = data.userInfo;
            				getApp().globalData.schoolList = data.schoolList;
            				getApp().kfPhone = data.kfPhone;
            				getApp().isLogin = true;
            				self.localSchool = data.schoolInfo.name;
            				self.schoolId = data.schoolInfo.id;
            				self.localSuccess = true;
            				self.pn = 1;
            				if (data.userInfo.wxapp_login <= 0) {
            					self.showWxappLogin = true;
            				}
            				self.listEvent(data.schoolList);
            				uni.setStorageSync('uid', data.userInfo.uid);
                            const index = self.school_list.findIndex(item => item === self.schoolId);
                            self.school_index = index;
                            self.cascadeVal=[self.prov_index,self.city_index,self.school_index];
                            self.firstShow = uni.getStorageSync('FIRSTSHOW') || 0;
                            if(!getApp().globalData.isRegisted  && self.firstShow == 0){
                                self.selectCity();
                                uni.setStorageSync('FIRSTSHOW',1);
                            }else{
                                self.loadNewPacket(2);
                            }
            			} else if (data.ok == 1) {
            				getApp().globalData.schoolInfo = data.schoolInfo;
            				getApp().globalData.userInfo = data.userInfo;
            				getApp().globalData.schoolList = data.schoolList;
            				getApp().kfPhone = data.kfPhone;
            				getApp().isLogin = true;
            				self.schoolId = data.schoolInfo.id;
            				self.localSuccess = true;
            				if (data.userInfo.wxapp_login <= 0) {
            					//self.setData({showWxappLogin: true});
            				}
            				self.listEvent(data.schoolList);
            				uni.setStorageSync('uid', data.userInfo.uid);
                            if(data.userInfo.bind_phone == 1){
                                getApp().globalData.isRegisted = true;
                                self.loadpacketList();
                            }else{
                                self.selectCity();
                            }
            			}
            		});
            	});
            },
            loadNewPacket: function(n){
                var self = this;
                var u_id = uni.getStorageSync('openid');
                var r_type = n;
                var school_id = this.schoolId || getApp().globalData.schoolId;
                $api_base.post($api_base.getRedpackeNew,{u_id:u_id,r_type:r_type,school_id:school_id},1).then(function(res) {
                	var data = res.data;
                    //if(data.ok==1){
                        getApp().globalData.isRegisted = true;
                        self.loadpacketList();;
                   // }
                })
            },
            getPhoneNumber: function(e){
                var self = this;
                if (e.detail.errMsg == 'getPhoneNumber:ok') {
                    $api_base.post($api_base.getDecryptData,{encryptedData: e.detail.encryptedData, iv: e.detail.iv,school_id: self.schoolId}).then(function (e) {
                        let data = e.data;
                        if(data.ok == 0){
                            getApp().globalData.isRegisted = false;
                            uni.showModal({
                             	title: '',
                             	content: '注册失败.',
                             	showCancel: false,
                             	confirmText: '知道了',
                             	confirmColor: '#00B89D',
                             	success(res) {
                             		if (res.confirm) {
                             			console.log('用户点击确定')
                             		} else if (res.cancel) {
                             			console.log('用户点击取消')
                             		}
                             	}
                            })
                        }else{ 
                            self.loginShow = false;
                            getApp().globalData.isRegisted = true;
                            uni.showToast({
                                title:'注册成功'
                            })
                            self.loadNewPacket(2);
                        }
                    })
                }else{
                    self.loadOver = false;
                    self.hideOver = false;
                    self.loginShow = false;
                    self.bindPhoneShow = true;
                    getApp().globalData.isRegisted = false;
                }
            },
            onGetAuthorize: function(res){
                var self = this;
                my.getPhoneNumber({
                    success: (res) => {
                        let encryptedData = res.response;
                        console.log(res);
                        $api_base.post($api_base.getDecryptData,res).then(function (e) {
                            let data = e.data;
                            if(data.ok == 0){
                                getApp().globalData.isRegisted = false;
                                uni.showModal({
                                 	title: '',
                                 	content: '注册失败.',
                                 	showCancel: false,
                                 	confirmText: '知道了',
                                 	confirmColor: '#00B89D',
                                 	success(res) {
                                 		if (res.confirm) {
                                 			console.log('用户点击确定')
                                 		} else if (res.cancel) {
                                 			console.log('用户点击取消')
                                 		}
                                 	}
                                })
                            }else{ 
                                self.loginShow = false;
                                getApp().globalData.isRegisted = true;
                                uni.showToast({
                                    title:'注册成功'
                                })
                                self.loadNewPacket(2);
                            }
                        })
                    },
                    fail: (res) => {
                        console.log(res);
                        console.log('getPhoneNumber_fail');
                        self.bindPhoneShow = true;
                        self.loadOver = false;
                        self.hideOver = false;
                    },
                });
            },
            onAuthError(e) {  
                self.loadOver = false;
                self.hideOver = false;
                this.loginShow = false;
                this.bindPhoneShow = true;
                getApp().globalData.isRegisted = false;
            }, 
            activeTimeEvent: function (s) {
                var self = this;
                s--
                self.s = s;
                if(s>0){
                    self.activeTimer = setTimeout(function () {
                        self.activeTimeEvent(self.s);
                    }, 1000); 
                }else{
                    clearTimeout(self.activeTimer);
                }  
            }, 
            loadpacketList: function(){
                var self = this;
                getApp().globalData.schoolId = self.schoolId;
                var param = {
                    u_id     : uni.getStorageSync('openid'),
                    red_id   : self.rp_id
                };
                $api_base.post($api_base.luckeyRedpacketList,param).then(function(res) {
                    let data = res.data;
                    if (data.ok == 1) {
                        self.mine_packet = data.data.mine_packet || {};
                        self.all_packet  = data.data.all_packet || [];
                        self.new_redpacket = data.data.new_redpacket || {};
                        self.packet_num  = data.data.redpacket_num || 0;
                        if(!self.mine_packet.reduction) self.no_get = true;
                        if(self.all_packet.length > 0){
                            const index1 = self.all_packet.findIndex(item => item.is_mine == 1);
                            const index2 = self.all_packet.findIndex(item => item.is_max == 1);
                            if(index2>=0){
                                self.hasMax = true;
                                if(index1>=0 && index1 == index2){
                                    self.mineIsMax = true;
                                }  
                            }
                        }   
                    }else if(data.ok == 50){
                        self.no_right = true;
                        self.packet_num  = data.data.redpacket_num || 0;
                    }
                    self.loadOver = false;
                    self.hideOver = false;
                });
            },
            selectCity: function() {
            	var animation = uni.createAnimation({
            		duration: 300,
            		timingFunction: 'ease'
            	});
            	this.animation = animation;
            	animation.height(1332 + 'rpx').step();
            	this.animationData = animation.export();
            },
            bindChange: function(e) {
            	const val = e.detail.value;
            	this.prov_index = val[0];
            	this.city_index = val[1];
            	this.school_index = val[2];
            	this.listEvent(getApp().globalData.schoolList);
            },
            enterEvent: function() {
                var self = this;
            	var animation = uni.createAnimation({
            		duration: 500,
            		timingFunction: 'ease',
            	});
            	var selectData = this.selectRegion;
            	this.animation = animation;
            	animation.height(0 + 'rpx').step()
            	this.animationData = animation.export();
            	this.schoolId = this.selectSchoolId;
            	getApp().globalData.schoolInfo = {
            		id: this.selectSchoolId,
            		name: selectData.school
            	};
                if(getApp().globalData.userInfo.bind_phone == 0){
                    self.loginShow = true;
                }else{
                    self.loadNewPacket(2);
                    
                }
            },
            cancelEvent: function() {
            	var animation = uni.createAnimation({
            		duration: 500,
            		timingFunction: 'ease'
            	})
            	this.animation = animation
            	animation.height(0 + 'rpx').step()
            	this.animationData = animation.export();
            	this.selectRegion = {};
            },
            phoneEvent: function (e) {
            	this.phone= e.target.value;
                this.verified = false;
                this.isOK = false;
            },
            getCode: function(e){
                if(this.phone.length != 11 || !this.verified) return
                var self = this;
                self.activeTimeEvent(60);
                $api_base.post($api_base.getCode, {mobile:self.phone},1 ).then(function(res){
                    let data = res.data;
                    if(data.ok == 1){
                        self.sending = true;
                    }else{
                        uni.showToast({
                            title:data.msg,
                            duration:1000
                        })
                    }
                });
            },
            codeEvent: function (e) {
                this.code= e.target.value;
                if(this.phone.length==11 && this.code.length == 4 && this.verified){
                    this.isOK = true;
                }
            },
            mverify: function(e){
                this.verified = e.msg;
            },
            submit: function(){
                var self = this;
                if(!this.isOK) return
                $api_base.post($api_base.bindPhone, {mobile:self.phone,code:self.code},1 ).then(function(res){
                    let data = res.data;
                    if(data.ok == 1){
                        uni.showToast({
                            title:'登录成功',
                            duration:1000
                        })
                        getApp().globalData.isRegisted = true;
                        self.loginShow = false;
                        self.bindPhoneShow = false;
                        self.loadNewPacket(2);
                    }else{
                        uni.showToast({
                            title:'登录失败',
                            duration:1000
                        })
                    }
                });
            },
            listEvent: function(allData) {
            	var self = this;
            	var prov = [];
            	var city = [];
            	var school = [];
            	var school_list = [];
            	var city_index = self.city_index;
            	var prov_index = self.prov_index;
            	var school_index = self.school_index;
            	var str_func = function(e) {
            		if (e.substr(-1, 1) == '市') {
            			e = e.substr(0, e.length - 1);
            		}
            		return e;
            	}
            	for (let i = 0; i < allData.length; i++) {
            		prov.push(allData[i].name)
            	}
            	if (allData[prov_index].regions) {
            		if (allData[prov_index].regions[city_index]) {
            			for (let i = 0; i < allData[prov_index].regions.length; i++) {
            				city.push(str_func(allData[prov_index].regions[i].name));
            			}
            			if (allData[prov_index].regions[city_index].regions) {
            				for (let i = 0; i < allData[prov_index].regions[city_index].regions.length; i++) {
            					school.push(str_func(allData[prov_index].regions[city_index].regions[i].name));
            					school_list.push(allData[prov_index].regions[city_index].regions[i].id);
            				}
            			}
            		}
            	} else {
            		city.push(str_func(allData[prov_index].name));
            	}
            	self.prov = prov;
            	self.city = city;
            	self.school = school;
            	self.school_list = school_list;
            	if (prov.length == 0 || city.length == 0) {
            		self.listEvent(getApp().globalData.schoolList);
            	}
            	self.selectRegion = {
            		prov: prov[self.prov_index],
            		city: city[self.city_index],
            		school: school[self.school_index],
            	};
            	self.selectSchoolId = school_list[self.school_index];
            },
            goHome: function () {
            	var schoolId = getApp().globalData.schoolId || 0;
            	uni.switchTab({
            		url: '/pages/index/index'
            	});
            },
			
		}
	}
</script>
<style>
  page {
  background-color: #FF9717;
  }
</style>
<style lang="scss" scoped>
	@import '../index.scss';
    @import 'index.scss';
</style>

